// SPDX-License-Identifier: GPL-3.0-or-later

import QtQuick
import Qt5Compat.GraphicalEffects

import Fk
import Fk.Components.LunarLTK.Photo

Item {
  id: root

  property var self
  property alias handcardArea: handcardAreaItem

  property string pending_skill: ""
  property string self_role: ""
  property int self_seat: 0
  property bool sortable: true
  property bool isGold: false
  property var pending_card
  property var pendings: [] // int[], store cid
  property int selected_card: -1

  property alias skillButtons: skillPanel.skill_buttons
  property alias attachedSkillButtons: attachedSkillPanel.skill_buttons

  property var disabledSkillNames: []

  signal cardSelected(var card)

  HandcardArea {
    id: handcardAreaItem
    height: parent.height * 0.78
    anchors.right: parent.right
    anchors.rightMargin: 150
    anchors.left: parent.left
    anchors.leftMargin: 10
    anchors.bottom: parent.bottom
    anchors.bottomMargin: -3
    onWidthChanged: updateCardPosition(true);
  }

  Image {
    id: seatImg
    source: Cpp.path + "/packages/lunarltk-qsgs-ui/image/selfArea/dashboard-seat.png"
    anchors.right: parent.right
    anchors.bottom: parent.bottom
    anchors.bottomMargin: 1
    height: 30
    fillMode: Image.PreserveAspectFit

    Text {
      property var seatChr: [
        "零", "一", "二", "三", "四", "五", "六",
        "七", "八", "九", "十", "十一", "十二",
      ]
      text: seatChr[root.self_seat]
      x: 4.5
      y: 5
      font.pixelSize: 19
      font.bold: true
      color: '#940000'
      font.family: Config.li2Name
    }

  }

  RoleComboBox {
    id: selfRole
    value: root.self_role
    anchors.top: parent.top
    anchors.topMargin: 1
    anchors.right: parent.right
    height: 30
    width: 30
  }

  AttachedSkillArea {
    id: attachedSkillPanel
    anchors.bottom: parent.top
    anchors.right: parent.right
    anchors.bottomMargin: 5
    anchors.rightMargin: 53
  }

  SkillArea {
    id: skillPanel
    anchors.bottom: parent.bottom
    anchors.right: parent.right
    anchors.bottomMargin: 2
    anchors.rightMargin: 32
  }

  Connections {
    target: handcardAreaItem
    function onCardSelected(cardId, selected) {
      Lua.call("UpdateRequestUI", "CardItem", cardId, "click", { selected, autoTarget: Config.autoTarget } );
    }
    function onCardDoubleClicked(cardId, selected) {
      Lua.call("UpdateRequestUI", "CardItem", cardId, "doubleClick", { selected, doubleClickUse: Config.doubleClickUse, autoTarget: Config.autoTarget } );
    }
    function onLengthChanged() {
      self.handcards = handcardAreaItem.length;
    }
  }

  function disableAllCards() {
    handcardAreaItem.enableCards([]);
  }

  function unSelectAll(expectId) {
    handcardAreaItem.unselectAll(expectId);
  }

  function addSkill(skill_name, prelight) {
    if (skill_name.endsWith('&')) {
      attachedSkillPanel.addSkill(skill_name, prelight);
    } else {
      skillPanel.addSkill(skill_name, prelight);
    }
  }

  function loseSkill(skill_name, prelight) {
    if (skill_name.endsWith('&')) {
      attachedSkillPanel.loseSkill(skill_name, prelight);
    } else {
      skillPanel.loseSkill(skill_name, prelight);
    }
  }

  function prelightSkill(skill_name, prelight) {
    for (let i = 0; i < skillButtons.count; i++) {
      const btn = skillButtons.itemAt(i);
      if (btn.orig === skill_name && btn.isFakeSkill) {
        btn.prelighted = prelight;
        btn.enabled = true;
      }
    }
  }

  function disableSkills() {
    disabledSkillNames = [];
    for (let i = 0; i < skillButtons.count; i++) {
      const item = skillButtons.itemAt(i);
      if (item.isActiveSkill) {
        item.enabled = false;
      }
    }
    for (let i = 0; i < attachedSkillButtons.count; i++) {
      const item = attachedSkillButtons.itemAt(i);
      if (item.isActiveSkill) {
        item.enabled = false;
      }
    }
  }

  function tremble() {
    self.tremble();
  }

  function updateHandcards() {
    Lua.call("FilterMyHandcards");
    handcardAreaItem.cards.forEach(v => {
      v.setData(Lua.call("GetCardData", v.cid, true));
    });
  }

  function update(nonEquipSkills) {
    unSelectAll();
    disableSkills();
    sortable = handcardAreaItem.sortable;

    let cards = handcardAreaItem.cards;
    const toRemove = [];
    for (let c of cards) {
      toRemove.push(c.cid);
      c.origY += 30;
      c.origOpacity = 0
      c.goBack(true);
      c.destroyOnStop();
    }
    handcardAreaItem.remove(toRemove);

    skillPanel.clearSkills();
    attachedSkillPanel.clearSkills();

    for (let s of nonEquipSkills) {
      addSkill(s);
    }

    cards = roomScene.drawPile.remove(Lua.call("GetPlayerHandcards", Self.id));
    handcardAreaItem.add(cards);
  }

  function applyChange(uiUpdate) {
    // TODO: 先确定要不要展开相关Pile
    // card - HandcardArea
    const parentPos = roomScene.mapFromItem(self, 0, 0);
    const component = Qt.createComponent(Cpp.path + "/packages/lunarltk-qsgs-ui/qml/lunarltk/components/dashboard/CardItem.qml");

    uiUpdate["_delete"]?.forEach(data => {
      if (data.type == "CardItem" && data.ui_data.footnote !== "$Equip") {
        const card = handcardAreaItem.remove([data.id])[0];
        card.origX = parentPos.x;
        card.origY = parentPos.y;
        card.destroyOnStop();
        card.goBack(true);
      }
    });
    uiUpdate["_new"]?.forEach(dat => {
      const sortable = Lua.call("CanSortHandcards", Self.id);
      if (dat.type == "CardItem" && dat.ui_data.footnote !== "$Equip") {
        const data = Lua.call("GetCardData", dat.data.id);
        data.x = parentPos.x;
        data.y = parentPos.y;
        const card = component.createObject(roomScene, data);
        card.footnoteVisible = true;
        card.markVisible = false;
        card.footnote = Lua.tr(dat.ui_data.footnote);
        const vcard = Lua.call("GetVirtualEquipData", 0, dat.data.id);
        if (vcard) {
          card.virt_name = vcard.name;
        }
        card.draggable = sortable;
        handcardAreaItem.add(card);
      }
    });
    handcardAreaItem.applyChange(uiUpdate);
    sortable = handcardAreaItem.sortable;
    // skillBtn - SkillArea
    const skDatas = uiUpdate["SkillButton"]
    skDatas?.forEach(skdata => {
      for (let i = 0; i < skillButtons.count; i++) {
        const skillBtn = skillButtons.itemAt(i);
        if (skillBtn.orig == skdata.id) {
          skillBtn.enabled = skdata.enabled;
          skillBtn.pressed = skdata.selected;
          break;
        }
      }
      for (let i = 0; i < attachedSkillButtons.count; i++) {
        const skillBtn = attachedSkillButtons.itemAt(i);
        if (skillBtn.orig == skdata.id) {
          skillBtn.enabled = skdata.enabled;
          skillBtn.pressed = skdata.selected;
          break;
        }
      }
    });

    pending_skill = Lua.call("GetPendingSkill");
  }
}
